//
//  MapViewController.m
//  NBTripe
//
//  Created by Lee on 16/1/18.
//  Copyright © 2016年 Vicki. All rights reserved.
//

#import "MapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "LTAnnotation.h"
@interface MapViewController ()<CLLocationManagerDelegate, MKMapViewDelegate>

@property (strong, nonatomic)  UILabel *location;

//除了提供位置跟踪功能之外，在定位服务中还包含CLGeocoder类用于处理地理编码和逆地理编码（又叫反地理编码）功能。
//地图
@property (nonatomic, strong) MKMapView *mapView;

@property (nonatomic, strong)   CLGeocoder *geocoder;
//CLLocationManager 是定位服务管理类，通过它可以设置定位服务的参数、获取经纬度等。
@property (nonatomic, strong)  CLLocationManager *locationManager;
//经度
@property (strong, nonatomic)  UILabel *longitude;
//纬度
@property (strong, nonatomic)  UILabel *latitude;
//map数组
@property (nonatomic, strong) NSArray *mapArr;


@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self getMapData];
    [self judgeSwitch];
    [self initializeLocationService];
    [self createMapview];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
}
//点击button更新地图
//- (IBAction)locationButton:(UIButton *)sender {
//    [self.locationManager startUpdatingLocation];
//}
- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    [_locationManager startUpdatingLocation];
}
- (void)judgeSwitch {
    //判断用户定位服务是否开启
        if ([CLLocationManager locationServicesEnabled]) {
                //开始定位用户的位置
                 [self.locationManager startUpdatingLocation];
                 //每隔多少米定位一次（这里的设置为任何的移动）
                 self.locationManager.distanceFilter=kCLDistanceFilterNone;
                //设置定位的精准度，一般精准度越高，越耗电（这里设置为精准度最高的，适用于导航应用）
                 self.locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
             }else
                 {
                     NSLog(@"error");
                     //不能定位用户的位置
                        //1.提醒用户检查当前的网络状况
                         //2.提醒用户打开定位开关
                    }
}
/**
 *  创建地图
 */
- (void)createMapview {
    self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.delegate = self;
    //定位的形式
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    //定位的类型
    self.mapView.mapType = MKMapTypeHybrid;
    // 是否可以缩放
    self.mapView.zoomEnabled = YES;
    // 是否可以滚动
    self.mapView.scrollEnabled =YES;
    // 是否可以旋转
    self.mapView.rotateEnabled = YES;
    // 是否显示3D
    self.mapView.pitchEnabled = NO;
    // 设置地图其它属性（显示）
    // 是否显示指南针
    self.mapView.showsCompass = YES;
    // 是否显示比例尺
    self.mapView.showsScale = YES;
    // 是否显示交通
    self.mapView.showsTraffic = YES;
    self.mapView.showsBuildings = YES;
    [self.view addSubview:self.mapView];
}

/**
 *  获取map数据
 */
- (void)getMapData {
    [XYNetWorkTool getWithUrl:kRecommendMapURL(_join_id) parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSDictionary *dic = result;
        self.mapArr = [dic objectForKey:@"trackpoints"];
        [self setRegin];
        [self addcoordinatetitle];
    } fail:nil];
}
/**
 *   根据调整的合适区域跨度 设置地图的显示区域
 */
- (void)setRegin {
    
    // 根据调整的合适区域跨度 设置地图的显示区域
     NSArray *arrs = [self.mapArr objectAtIndex:1];
    CLLocationCoordinate2D center = self.mapView.region.center;
    MKCoordinateSpan span = MKCoordinateSpanMake([arrs[1] doubleValue], [arrs[2] doubleValue]);
       MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
     [self.mapView setRegion:region animated:YES];
    for (int i = 0; i <self.mapArr.count ; i++) {
        NSArray *arr = [self.mapArr objectAtIndex:i];
//        // 根据调整的合适区域跨度 设置地图的显示区域
//        MKCoordinateSpan span = MKCoordinateSpanMake([arr[2] doubleValue], [arr[1] doubleValue]);
        NSLog(@"纬度：%@, 经度： %@", arr[2], arr[1]);
//        CLLocationCoordinate2D center = self.mapView.region.center;
//        MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
        [self getAddressByLatitude:[arr[1] doubleValue] longitude:[arr[2] doubleValue]];
//        [self.mapView setRegion:region animated:YES];

}
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}

/**
 *  根据地理坐标取得地名
 */
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude {
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    //设置经度和纬度
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"详细信息:%@",placemark.addressDictionary);
    }];

}
/**
 *  在需要使用大头针的方法类中，添加一个大头针
 */
- (void)addcoordinatetitle {
         // 将坐标转换为经纬度
    for (int i = 0; i <self.mapArr.count ; i++) {
        NSArray *arr = [self.mapArr objectAtIndex:i];
        CGPoint Point = CGPointMake([arr[1] doubleValue], [arr[2] doubleValue]);
         CLLocationCoordinate2D center = [self.mapView convertPoint:Point toCoordinateFromView:self.mapView];
         [self addAnnotationWithCoordinate:center];
    }
    
}
 - (void)addAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate
 {
     
         LTAnnotation *annotation = [[LTAnnotation alloc] init];
    
         annotation.coordinate = coordinate;
         annotation.coordinatetitle = @"aaa";
         annotation.subtitles = @"bbb";
         [self.mapView addAnnotation:annotation];
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
